package com.baichang.taoshunda.service.impl;

import com.baichang.framework.Constant;
import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.model.Page;
import com.baichang.framework.utils.*;
import com.baichang.sms.utils.SMSUtils;
import com.baichang.taoshunda.SMSConstants;
import com.baichang.taoshunda.dao.*;
import com.baichang.taoshunda.entity.Bussiness;
import com.baichang.taoshunda.entity.Carousel;
import com.baichang.taoshunda.entity.CompanyBalance;
import com.baichang.taoshunda.entity.em.currencyCode;
import com.baichang.taoshunda.service.*;
import com.baichang.taoshunda.utils.MsgUtils;
import com.baichang.taoshunda.utils.RongYunUtils;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ${wushenglu} on 2017/8/18 0018.
 */
@Service
public class BusinessServiceImpl implements BusinessService {


    @Autowired
    private BussinessDao bussinessDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private FavoritesDao favoritesDao;
    @Autowired
    private CouponDao couponDao;
    @Autowired
    private PromotionDao promotionDao;

    @Autowired
    private CompanyBalanceDao companyBalanceDao;

    @Autowired
    private CarouselDao carouselDao;

    @Autowired
    private TrendsUserService trendsUserService;

    @Autowired
    private CityService cityService;
    @Autowired
    private GoodsCommentDao goodsCommentDao;

    @Autowired
    private ParamsService paramsService;

    @Autowired
    private RecommendCompanyDao recommendCompanyDao;

    @Autowired
    private CompanyPanymentHistoryDao companyPanymentHistoryDao;

    @Autowired
    private BusinessMoneyRecordDao businessMoneyRecordDao;

    @Autowired
    private OrderDetailsDao orderDetailsDao;
    @Autowired
    private RyFriendService ryFriendService;

    @Autowired
    private TrendService trendService;

    @Autowired
    private BussMsgService bussMsgService;

    /**
     * 根据城市编号获取对应的推荐商家
     *
     * @param cityId 城市编号
     * @param lat
     * @param lng    @return
     */
    @Override
    public List<Map<String, Object>> getRecommendBussiness(Integer cityId, String lat, String lng) {
        return bussinessDao.getRecommendBussiness(cityId, lng, lat);
    }

    /**
     * 查询商家列表
     *
     * @param startCreate
     * @param startTime
     * @param endTime
     * @param cityId
     * @param typeId
     * @param name
     * @param nowPage
     * @param pageSize    @return
     */
    @Override
    public Page queryBusinessList(String startCreate, String endCreate, String startTime, String endTime, Integer cityId, Integer typeId, String name, int nowPage, int pageSize) {
        return bussinessDao.queryBusinessList(startCreate, endCreate, startTime, endTime, cityId, typeId, name, nowPage, pageSize);
    }

    /**
     * 商家订单查询
     *
     * @param
     * @param
     * @param id
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page<Map<String, Object>> businessOrderList(Integer id, int nowPage, int pageSize) {
        return bussinessDao.businessOrderList(id, nowPage, pageSize);
    }

    /**
     * 商家明细查询
     *
     * @param id
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page<Map<String, Object>> businessOrderDetails(Integer id, int nowPage, int pageSize) {
        return bussinessDao.businessOrderDetails(id, nowPage, pageSize);
    }

    /**
     * 修改商家账号
     *
     * @param id
     * @param pwd
     * @return
     */
    @Override
    public int updateBusinessAccount(Integer id, String pwd) {
        String passWord = MD5Util.md5(pwd);
        return bussinessDao.updateBusinessAccount(id, passWord);
    }

    /**
     * 商家启用、禁用
     *
     * @param id
     * @param state
     * @return
     */
    @Override
    public int updateStatus(Integer id, Integer state) throws ServiceException {
//        if (state == 2) {
//            Map<String, Object> map = bussinessDao.queryBusInfo(id);
//            Map<String, Object> maps = carouselDao.queryBusInfo(id);
//            Integer recommend = Integer.parseInt(map.get("isRecommend").toString());
//            if (recommend == 1) {
//                throw new ServiceException("该商家是诚信商家不可禁用");
//            }
//            if (maps != null) {
//                throw new ServiceException("该商家有广告位不可禁用");
//            }
//        }
        return bussinessDao.updateStatus(id, state);
    }

    /**
     * 修改商家信息
     *
     * @param id
     * @param bussName
     * @param bussId
     * @param bussPhone
     * @param serviceTel
     * @param address
     * @param cityId
     * @param serviceLince
     * @param bussLicnese
     * @return
     */
    @Override
    public int updateBusinessInfo(Integer id, String bussName, Integer bussId, String bussPhone, String serviceTel, String address, Integer cityId, Integer areaId, String serviceLince, String bussLicnese, String remarks) {
        Map map = new HashedMap();
        map.put("bussName", bussName);
        map.put("bussTypeId", bussId);
        map.put("bussPhone", bussPhone);
//        map.put("bussTel", serviceTel);
        map.put("adress", address);
        map.put("cityId", cityId);
        map.put("areaId", areaId);
        map.put("serviceLince", serviceLince);
        map.put("bussLicnese", bussLicnese);
        map.put("serviceRemark", remarks);
        return bussinessDao.update(map, id);
    }

    /**
     * 推荐诚信商家
     *
     * @param id
     * @param isRecommend
     * @return
     */
    @Override
    public int updateRecommend(Integer id, Integer isRecommend, Integer state) throws ServiceException {
        if (state == 2) {
            throw new ServiceException("该商家已被禁用");
        }
        bussinessDao.updateSort(id);
        Map<String, Object> isRecommends = bussinessDao.getIsRecommend();
        String str = isRecommends.get("recommend").toString();
        Integer in = Integer.parseInt(str);
        if (in <= 10) {
            bussinessDao.updateRecommend(id, isRecommend);
        } else {
            throw new ServiceException("诚信商家超过十位");
        }
        return 0;
    }

    /**
     * 查询审核商家
     *
     * @param businessName
     * @param account
     * @param telephone
     * @param cityName
     * @param address
     * @param nowPage
     * @param pageSize     @return
     */
    @Override
    public Page queryBusinessAudit(String businessName, String account, String telephone, String cityName, String address, int nowPage, int pageSize) {
        return bussinessDao.queryBusinessAudit(businessName, account, telephone, cityName, address, nowPage, pageSize);
    }

    /**
     * 审核商家
     *
     * @param id
     * @param audit
     * @param logo
     * @param store
     * @param shop
     * @param legalCardPic
     * @param service      @return
     * @param licnese
     */
    @Override
    public boolean updateAudit(Integer id, Integer audit, String reason, String logo, String store, String shop, String legalCardPic, String service, String licnese) {
        Bussiness business = bussinessDao.getEntityById(id);
        Map map = new HashedMap();
        if (audit == 1) {
            map.put("storePic", store);
            map.put("shopPic", shop);
            map.put("legalCardPic", legalCardPic);
            map.put("serviceLince", service);
            map.put("audit", audit);
            map.put("bussLicnese", licnese);
            bussinessDao.update(map, id);
            return SMSUtils.sendMsg(business.getAccount(), SMSConstants.reviewAndPassThrough);
        } else {
            map.put("audit", audit);
            map.put("reason", reason);
            bussinessDao.update(map, id);
            return SMSUtils.sendMsg(business.getAccount(), SMSConstants.auditFailedToPass, reason);
        }
    }

    /**
     * 查询商家详情
     * 接口
     * 武圣路
     *
     * @param bussId 商家编号
     * @param ulat   纬度
     * @param ulng   经度
     * @param userId 用户编号
     * @return
     */
    @Override
    public Map<String, Object> getBussinessDateial(int bussId, double ulat, double ulng, int userId) throws ServiceException {
        Map<String, Object> map = bussinessDao.getBussinessDateial(bussId);
        if (ulat == 0D && ulng == 0D) {
            throw new ServiceException("请确认是否开启定位，并前往开阔地带！");
        }
        Bussiness business = bussinessDao.getEntityById(bussId);
//        if (map == null) {
//            throw new ServiceException("商家已被刪除或禁用");
//        }
        //获取商家的经纬度
        double buslng = Double.parseDouble(map.get("lng").toString());
        double buslat = Double.parseDouble(map.get("lat").toString());
        //计算距离
        double distace = Spatial4jUtil.getDistance(ulng, ulat, buslng, buslat);
        BigDecimal bigDecimal = new BigDecimal(distace);
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(5);
        distace = bigDecimal.setScale(2, RoundingMode.HALF_EVEN).doubleValue();
//        System.out.println(distace);
        //统计月售份额
        int orderCount = orderService.getCountByMouthAndBusssId(bussId);
        //统计商家的商品数量
        int goodsNumber = goodsDao.getCompanyGoodsNumber(bussId);
        //是否收藏
        int isFavorites = favoritesDao.getCountByUserAndBusId(bussId, userId, 1);
        //遍历获取商家的优惠劵
        List<Map<String, Object>> couponList = couponDao.getCouponByBussId(bussId);
//        StringBuffer sb = new StringBuffer();
//        for (int i = 0; i < couponList.size(); i++) {
//            sb.append(couponList.get(i).get("name"));
//            if (i > 0) {
//                sb.append("," + couponList.get(i).get("name"));
//            }
//        }
        map.put("couponList", couponList);
        //遍历获取商家的优惠活动
        List<Map<String, Object>> promotionList = promotionDao.getPromotionByBussId(bussId);
        StringBuffer promotion = new StringBuffer();
        if (promotionList.size() > 0) {
            for (int i = 0; i < promotionList.size(); i++) {
                if (i > 0) {
                    promotion.append(";  " + promotionList.get(i).get("name"));
                } else {
                    promotion.append(promotionList.get(i).get("name"));
                }

            }
            map.put("promotionList", promotion.toString());
        } else {
            map.put("promotionList", "");
        }
        map.put("startNumber", goodsCommentDao.getSartNum(bussId).get("starNum"));
        double dispatching = getDispatching(bussId, BigDecimal.valueOf(distace), 0);
        map.put("distace", distace);
        map.put("serviceLince", business.getServiceLince());
        map.put("bussLicnese", business.getBussLicnese());
        map.put("companyStatus", business.getState());
        map.put("otherLicenses", business.getOtherLicenses());
        map.put("otherLicensesTwo", business.getOtherLicensesTwo());
        map.put("orderCount", orderCount);
        map.put("goodsNumber", goodsNumber);
        map.put("isFavorites", isFavorites);
        map.put("dispatching", dispatching);
        map.put("RyToken", JSONObject.fromObject(business.getRyToken()).get("token"));
        map.put("RyId", JSONObject.fromObject(business.getRyToken()).get("userId"));
        return map;
    }

    /**
     * 查询商家列表
     *
     * @param cityId     城市编号
     * @param ulat       经度
     * @param ulng       纬度
     * @param typeId     查询类型 1综合排序  按照商家星数排
     *                   2 销量 月售量
     *                   3距离
     * @param nowPage    当前页
     * @param pageSize   @return
     * @param bussTypeId
     */
    @Override
    public List<Map<String, Object>> getBussinessList(int cityId, double ulat, double ulng, int typeId, int nowPage, int pageSize, int bussTypeId, int userId) throws ServiceException {
        //接收所有商家
        List<Map<String, Object>> mapList = bussinessDao.getBussinessList(typeId, cityId, nowPage, pageSize, bussTypeId, userId, ulat, ulng);
        for (int i = 0; i < mapList.size(); i++) {
            //获取商家编号
            int busId = Integer.parseInt(mapList.get(i).get("id").toString());
            //遍历获取商家的优惠劵
            List<Map<String, Object>> couponList = couponDao.getCouponByBussId(busId);
            if (couponList.size() > 0) {
                mapList.get(i).put("couponList", couponList);
            }
            //遍历获取商家的优惠活动
            List<Map<String, Object>> promotionList = promotionDao.getPromotionByBussId(busId);
            if (promotionList.size() > 0) {
                mapList.get(i).put("promotionList", promotionList.get(0).get("name"));
            } else {
                mapList.get(i).put("promotionList", "");
            }

        }
        //判断是否是按照距离排序
        if (typeId != 3) {
            int len = mapList.size();
            for (int i = 0; i < len; ++i) {
                Map item = mapList.get(i);
                int busId = Integer.parseInt(item.get("id").toString());
                if (null == item.get("lng") || null == item.get("lat")) {
                    throw new ServiceException("请在参数集合中设置经度(lng)和纬度(lat)");
                }
                double distance = Spatial4jUtil.getDistance(ulng, ulat, Double.valueOf(item.get("lng").toString()).doubleValue(), Double.valueOf(item.get("lat").toString()).doubleValue());
                BigDecimal bigDecimal = new BigDecimal(distance);
                item.put("distance", bigDecimal.setScale(2, RoundingMode.HALF_EVEN));
                double dispatching = getDispatching(busId, bigDecimal.setScale(2, RoundingMode.HALF_EVEN), 0);
                item.put("dispatching", dispatching);
            }
            return mapList;
        } else {
            try {
                mapList = Spatial4jUtil.getComparedList(ulng, ulat, mapList);
                for (int i = 0; i < mapList.size(); i++) {
                    Map item = mapList.get(i);
                    int busId = Integer.parseInt(item.get("id").toString());
                    BigDecimal bigDecimal = new BigDecimal(item.get("distance").toString());
                    double dispatching = getDispatching(busId, bigDecimal.setScale(2, RoundingMode.HALF_EVEN), 0);
                    item.put("dispatching", dispatching);
                }
                return mapList;
            } catch (Exception e) {
                e.printStackTrace();
                return mapList;
            }
        }

    }


    /**
     * 查询商家列表
     *
     * @param userId   用户编号
     * @param ulat     经度
     * @param ulng     纬度
     * @param nowPage  当前页
     * @param pageSize @return
     */
    @Override
    public List<Map<String, Object>> getBussinessListByUserId(int userId, double ulat, double ulng, int nowPage, int pageSize) throws ServiceException {
        //接收所有商家
        List<Map<String, Object>> mapList = bussinessDao.getBussinessListByUserId(userId, nowPage, pageSize, ulat, ulng);
        for (int i = 0; i < mapList.size(); i++) {
            System.out.println("ulat" + ulat + "ulng" + ulng);
            double distance = Spatial4jUtil.getDistance(ulng, ulat, Double.valueOf(mapList.get(i).get("lng").toString()).doubleValue(), Double.valueOf(mapList.get(i).get("lat").toString()).doubleValue());
            System.out.println("距离" + distance);
            BigDecimal bigDecimal = new BigDecimal(distance);
            mapList.get(i).put("distance", bigDecimal.setScale(2, RoundingMode.HALF_EVEN));
            double dispatching = getDispatching(Integer.parseInt(mapList.get(i).get("id").toString()), bigDecimal.setScale(2, RoundingMode.HALF_EVEN), 0);
            mapList.get(i).put("dispatching", dispatching);
            //获取商家编号
            int busId = Integer.parseInt(mapList.get(i).get("id").toString());
            //遍历获取商家的优惠劵
            List<Map<String, Object>> couponList = couponDao.getCouponByBussId(busId);
            if (couponList.size() > 0) {
                mapList.get(i).put("couponList", couponList);
            }
            //遍历获取商家的优惠活动
            List<Map<String, Object>> promotionList = promotionDao.getPromotionByBussId(busId);
            if (promotionList.size() > 0) {
                mapList.get(i).put("promotionList", promotionList.get(0).get("name"));
            } else {
                mapList.get(i).put("promotionList", "");
            }
        }
        return mapList;
    }

    /**
     * 获取配送费
     *
     * @param busId    商家编号
     * @param distance 距离
     * @return
     * @throws ServiceException
     */
    @Override
    public double getDispatching(int busId, BigDecimal distance, Integer isFree) throws ServiceException {
        //获取商家信息
        Bussiness bussiness = bussinessDao.getEntityById(busId);
        if (bussiness == null) {
            throw new ServiceException("商家不存在");
        }
        //查看商家是否免费配送
        int isDispatching = bussiness.getIsDispatching();
        //如果免费配送费为0
        if (isDispatching == 1 || isFree == 1) {
            return 0.0;
        } else {
            double qibuDistance = Double.parseDouble(paramsService.getParamsValue(31, 29).get("value").toString());
            //判断是否在起步范围内
            //不在起步内
            if (distance.doubleValue() > qibuDistance) {
                double paramsDistance = distance.doubleValue();
                double qibuMoney = Double.parseDouble(paramsService.getParamsValue(32, 30).get("value").toString());
                //超过起步距离每多少公里
                double passDiatance = Double.parseDouble(paramsService.getParamsValue(33, 31).get("value").toString());
                //超过起步距离每多少公里多少钱
                double passMoney = Double.parseDouble(paramsService.getParamsValue(34, 32).get("value").toString());
                double distance2 = paramsDistance - qibuDistance;
                //超出范围的次数
                double count = Math.floor(distance2 / passDiatance) + 1;
                if (distance2 > 20) {
                    return 7;
                } else {
                    return qibuMoney + passMoney * count;
                }

            } else {
                //起步内返回起步价
                double qibuMoney = Double.parseDouble(paramsService.getParamsValue(32, 30).get("value").toString());
                return qibuMoney;
            }
        }

    }


    /**
     * 手机号登录
     * 1.判断验证码
     * 2.返回商家信息
     *
     * @param mobile 手机号
     * @param code   验证码
     * @return
     */
    @Override
    public Map<String, Object> mobileMsgLogin(String mobile, String code) throws ServiceException {
        //1.判断手机号
        if (StringUtils.isEmpty(mobile)) {
            throw new ServiceException("手机号不能为空");
        }
        //2.判断是否发送验证码
        String redisCode = RedisUtil.get(Constant.SESSION_CODE_KEY + mobile);
        if (StringUtils.isEmpty(redisCode)) {
            throw new ServiceException("尚未发送验证码");
        }
        //3.判断验证码是否正确
        if (!code.equals(redisCode)) {
            throw new ServiceException("验证码不正确");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Bussiness bussiness = bussinessDao.getBussnessByPhone(mobile);
        if (bussiness == null) {
            throw new ServiceException("账号不存在");
        }
        if (bussiness.getAudit() != 1) {
            throw new ServiceException("请审核通过后再登录");
        }
        map.put("id", bussiness.getId());
        String token = TokenUtils.putValue(bussiness.toMap(), 30);
        map.put("token", token);
        bussinessDao.updateLastLoginTime(bussiness.getAccount());
        //环信
        map.put("hxName", bussiness.getHxName());
        map.put("hxName", bussiness.getHxPwd());
        int trendsUserId = trendsUserService.getTrendsUserIdByBussId(bussiness.getId());
        map.put("trendsUserId", trendsUserId);
        map.put("cityId", bussiness.getCityId());
        map.put("isOpen", bussiness.getIsOpen());
        map.put("startTime", bussiness.getStartTime());
        map.put("endTime", bussiness.getEndTime());
        return map;
    }

    /**
     * 账号密码登录
     * 1.判断账号是否存在
     * 2.判断密码是否正确
     * 3.返回商家信息
     *
     * @param account 账号
     * @param pwd     密码
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(String account, String pwd) throws ServiceException {
        Bussiness bussiness = bussinessDao.getBussnessByPhone(account);
        System.out.println("shhooohoho" + bussiness);
        if (bussiness == null) {
            throw new ServiceException("账号不存在");
        }
        if (!bussiness.getPwd().equals(MD5Util.md5(pwd))) {
            throw new ServiceException("密码不正确");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", bussiness.getId());
        String token = TokenUtils.putValue(bussiness.toMap(), 30);
        String hander = trendService.getToken(bussiness.getId(), 2).get("accessToken").toString();
        map.put("token", token);
        map.put("hander", hander);
        map.put("audit", bussiness.getAudit());
        map.put("id", bussiness.getId());
        //isAuthentication   0   未认证  1已认证
        map.put("isAuthentication", 1);
//            if (bussiness.getAudit() != 1 && bussiness.getRegisterNumber() == 3) {
//                throw new ServiceException("请审核通过后再登录");
//            }
        bussinessDao.updateLastLoginTime(account);
        //环信
        map.put("trendsUserId", trendService.getToken(bussiness.getId(), 2).get("uniqueId").toString());
        map.put("cityId", bussiness.getCityId());
        map.put("areaId", bussiness.getAreaId());
        map.put("provincesId", bussiness.getProvincesId());
        map.put("minCityId", bussiness.getMinCityId());
        map.put("isOpen", bussiness.getIsOpen());
        map.put("busName", bussiness.getBussName());
        map.put("cashPwd", bussiness.getCashPwd());
        map.put("startTime", bussiness.getStartTime());
        map.put("headPic", bussiness.getHeadPic());
        map.put("storePic", bussiness.getStorePic());
        map.put("endTime", bussiness.getEndTime());
        map.put("typeId", bussiness.getBussTypeId());
        map.put("RyToken", JSONObject.fromObject(bussiness.getRyToken()).get("token"));
        map.put("RyId", JSONObject.fromObject(bussiness.getRyToken()).get("userId"));
        map.put("legalPeople", bussiness.getLegalPeople());
        int isRecord = companyPanymentHistoryDao.getCountRecord(bussiness.getId());
        int isRecordReturn = businessMoneyRecordDao.getCountAboutStates(bussiness.getId());
        map.put("isRecord", isRecord);
        map.put("registerNumber", bussiness.getRegisterNumber());
        map.put("isRecordReturn", isRecordReturn);


        return map;
    }

    /**
     * 商家注册
     *
     * @param account             账号
     * @param code                验证码
     * @param pwd                 密码
     * @param mobile              电话号
     * @param servicePhone        业务电话
     * @param name                商家名称
     * @param area                地区
     * @param address             地址
     * @param cityId              城市编号
     * @param storePic            门头照
     * @param shopPic             店内照片
     * @param legalCardPic        法人身份证
     * @param bussLicnese         营业执照
     * @param serviceLince        服务许可证
     * @param lng                 经度
     * @param lat                 维度
     * @param legalPeople
     * @param emergenCycontact
     * @param emergencyContactTel @return
     * @param provinceId
     * @param areaId
     */
    @Override
    public Map<String, Object> register(String account, String code, String pwd, String mobile, String servicePhone, String name, String area, String address, Integer typeId, Integer cityId, String storePic, String shopPic, String legalCardPic, String bussLicnese, String serviceLince, String lng, String lat, String handheldPhotos, String fontCard, String reverseCard, String legalPeople, String emergenCycontact, String emergencyContactTel, Integer provinceId, Integer areaId) throws ServiceException {
        //2.判断是否发送验证码
//        String redisCode = RedisUtil.get(Constant.SESSION_CODE_KEY + account);
//        if (StringUtils.isEmpty(redisCode)) {
//            throw new ServiceException("尚未发送验证码");
//        }
        Bussiness bussiness = bussinessDao.getAuditBussnessByPhone(account);
        if (bussiness != null) {
            throw new ServiceException("该账号已经被注册");
        }
        if (bussiness != null) {
            if (bussiness.getAudit() == 3) {
                throw new ServiceException("请耐心等待审核");
            }
        }
        bussiness = new Bussiness();
        bussiness.setState(1);
        bussiness.setAccount(account);
        bussiness.setAdress(address);
        bussiness.setAudit(3);//需要审核
        bussiness.setBalance(new BigDecimal(0));
        bussiness.setBussCreousel("");
        bussiness.setBussInfo("");
        bussiness.setSex(" ");
        bussiness.setBussLicnese(bussLicnese);
        bussiness.setBussLogo("");
        bussiness.setBussName(name);
        bussiness.setRegisterNumber(3);
        bussiness.setBussPhone(mobile);
        bussiness.setUserId(0);
        bussiness.setFreezeMoney(BigDecimal.valueOf(0));
        bussiness.setBussTel(servicePhone);
        bussiness.setBussTypeId(typeId);
        if (provinceId == 0) {
            throw new ServiceException("请正确选择你所在城市的省份");
        } else {
            if (areaId != 0) {
                bussiness.setProvincesId(provinceId);
                bussiness.setAreaId(areaId);
                bussiness.setCityId(cityId);
                bussiness.setMinCityId(areaId);
            } else if (areaId == 0 && cityId != 0) {
                bussiness.setProvincesId(provinceId);
                bussiness.setAreaId(0);
                bussiness.setCityId(cityId);
                bussiness.setMinCityId(cityId);
            } else {
                throw new ServiceException("请正确选择你所在城市的市区");
            }
        }
        bussiness.setCityId(cityId);
        bussiness.setCreated(new Date());
        bussiness.setDispatching(new BigDecimal(0));
        bussiness.setHeadPic("");
        bussiness.setIdCard("");
        bussiness.setIsInvoice(0);
        bussiness.setIsRecommend(0);
        bussiness.setLat(lat);
        bussiness.setLegalCardPic(legalCardPic);
        bussiness.setLegalPeople(legalPeople);
        bussiness.setLng(lng);
        bussiness.setPwd(MD5Util.md5(pwd));
        bussiness.setReason("");
        bussiness.setServiceLince(serviceLince);
        bussiness.setShopPic(shopPic);
        bussiness.setStartTime("00:00");
        bussiness.setEndTime("23:00");
        bussiness.setEmergencyContact(emergenCycontact);
        bussiness.setEmergencyContactTel(emergencyContactTel);
        bussiness.setState(1);
        bussiness.setStorePic(storePic);
        bussiness.setHandheldPhotos(handheldPhotos);
        bussiness.setFontCard(fontCard);
        bussiness.setReverseCrad(reverseCard);
        bussiness.setArea(area);
        bussiness.setIsPosition(0);
        bussiness.setIsOpen(2);
        bussiness.setCashPwd("");
        Long bussId = bussinessDao.save(bussiness);
        Map<String, Object> map = new HashMap<String, Object>();
        trendService.saveUser(account, pwd, bussId.intValue(), name, servicePhone, "", 2);
        map.put("id", bussId);
        String header = trendService.getToken(bussId.intValue(), 2).get("accessToken").toString();
        String trendsUserId = "";
        trendsUserId = trendService.getToken(bussId.intValue(), 2).get("uniqueId").toString();
        map.put("trendsUserId", trendsUserId);
        String ryToken = RongYunUtils.getRYToken("company" + bussId, name, storePic);
        System.out.println(ryToken);
        bussinessDao.updateRYToken(bussId, ryToken, trendsUserId);
        String token = TokenUtils.putValue(map, 30);
        //修改最后登录时间
        bussinessDao.updateLastLoginTime(account);
        //添加互动用户表中
        trendsUserService.addTrendsUser(0, bussId.intValue());
        map.put("token", token);
        map.put("header", header);
//        map.put("id", bussiness.getId());
        map.put("cityId", bussiness.getCityId());
        map.put("isOpen", bussiness.getIsOpen());
        map.put("startTime", bussiness.getStartTime());
        map.put("endTime", bussiness.getEndTime());
        return map;
    }


    /**
     * 邀请商家 补全认证信息
     *
     * @param account             账号
     * @param mobile              电话号
     * @param servicePhone        业务电话
     * @param name                商家名称
     * @param area                地区
     * @param address             地址
     * @param cityId              城市编号
     * @param storePic            门头照
     * @param shopPic             店内照片
     * @param legalCardPic        法人身份证
     * @param bussLicnese         营业执照
     * @param serviceLince        服务许可证
     * @param lng                 经度
     * @param lat                 维度
     * @param legalPeople
     * @param emergenCycontact
     * @param emergencyContactTel @return
     * @param provinceId
     * @param areaId
     */
    @Override
    public Map<String, Object> authentication(String account, String mobile, String servicePhone, String name, String area, String address, Integer typeId, Integer cityId, String storePic, String shopPic, String legalCardPic, String bussLicnese, String serviceLince, String lng, String lat, String handheldPhotos, String fontCard, String reverseCard, String legalPeople, String emergenCycontact, String emergencyContactTel, Integer provinceId, Integer areaId) throws ServiceException {

        Bussiness bussiness = bussinessDao.getAuditBussnessByPhone(account);
        bussiness.setState(1);
        bussiness.setAccount(account);
        bussiness.setAdress(address);
        bussiness.setAudit(3);//需要审核
        bussiness.setBalance(new BigDecimal(0));
        bussiness.setBussCreousel("");
        bussiness.setBussInfo("");
        bussiness.setSex(" ");
        bussiness.setBussLicnese(bussLicnese);
        bussiness.setBussLogo("");
        bussiness.setBussName(name);
        bussiness.setBussPhone(mobile);
        bussiness.setFreezeMoney(BigDecimal.valueOf(0));
        bussiness.setBussTel(servicePhone);
        bussiness.setBussTypeId(typeId);
        if (provinceId == 0) {
            throw new ServiceException("请正确选择你所在城市的省份");
        } else {
            if (areaId != 0) {
                bussiness.setProvincesId(provinceId);
                bussiness.setAreaId(areaId);
                bussiness.setCityId(cityId);
                bussiness.setMinCityId(areaId);
            } else if (areaId == 0 && cityId != 0) {
                bussiness.setProvincesId(provinceId);
                bussiness.setAreaId(0);
                bussiness.setCityId(cityId);
                bussiness.setMinCityId(cityId);
            } else {
                throw new ServiceException("请正确选择你所在城市的市区");
            }
        }
        bussiness.setCityId(cityId);
        bussiness.setCreated(new Date());
        bussiness.setDispatching(new BigDecimal(0));
        bussiness.setHeadPic("");
        bussiness.setIdCard("");
        bussiness.setIsInvoice(0);
        bussiness.setIsRecommend(0);
        bussiness.setLat(lat);
        bussiness.setLegalCardPic(legalCardPic);
        bussiness.setLegalPeople(legalPeople);
        bussiness.setLng(lng);
        bussiness.setReason("");
        bussiness.setServiceLince(serviceLince);
        bussiness.setShopPic(shopPic);
        bussiness.setStartTime("00:00");
        bussiness.setEndTime("23:00");
        bussiness.setEmergencyContact(emergenCycontact);
        bussiness.setEmergencyContactTel(emergencyContactTel);
        bussiness.setState(1);
        bussiness.setStorePic(storePic);
        bussiness.setHandheldPhotos(handheldPhotos);
        bussiness.setFontCard(fontCard);
        bussiness.setReverseCrad(reverseCard);
        bussiness.setArea(area);
        bussiness.setIsPosition(0);
        bussiness.setIsOpen(2);
        bussiness.setCashPwd("");
        //修改信息  换成修改信息
        Integer bussId = bussiness.getId();
        int a = bussinessDao.update(bussiness);
        System.out.println("sssssss" + a);
        Map<String, Object> map = new HashMap<String, Object>();
        //互动信息 要修改不？？x需要修改
        trendService.updateUser(account, bussiness.getPwd(), bussId.intValue(), name, servicePhone, "", 2);
        map.put("id", bussId);
        String header = trendService.getToken(bussId.intValue(), 2).get("accessToken").toString();
        String trendsUserId = "";
        trendsUserId = trendService.getToken(bussId.intValue(), 2).get("uniqueId").toString();
        map.put("trendsUserId", trendsUserId);
        String ryToken = RongYunUtils.getRYToken("company" + bussId, name, storePic);
        System.out.println(ryToken);
        bussinessDao.updateRYToken(Long.valueOf(bussId), ryToken, trendsUserId);
        String token = TokenUtils.putValue(map, 30);
        //修改最后登录时间
        bussinessDao.updateLastLoginTime(account);
        map.put("token", token);
        map.put("header", header);
//        map.put("id", bussiness.getId());
        map.put("cityId", bussiness.getCityId());
        map.put("isOpen", bussiness.getIsOpen());
        map.put("startTime", bussiness.getStartTime());
        map.put("endTime", bussiness.getEndTime());
        return map;
    }

    /**
     * 邀请商家注册
     *
     * @param account        账号
     * @param code           验证码
     * @param pwd            密码
     * @param registerNumber
     */
    @Override
    public Map<String, Object> businessregister(String account, String code, String pwd, Integer userId, Integer registerNumber) throws ServiceException {
        bussMsgService.checkCodeMsg(account, code);
        Bussiness bussiness = bussinessDao.getAuditBussnessByPhone(account);
        if (bussiness != null) {
            throw new ServiceException("该账号已经被注册");
        }
        if (bussiness != null) {
            if (bussiness.getAudit() == 3) {
                throw new ServiceException("请耐心等待审核");
            }
        }
        bussiness = new Bussiness();
        bussiness.setState(1);
        bussiness.setUserId(userId);//邀请人的用户id
        bussiness.setAccount(account);
        bussiness.setAudit(3);//需要审核
        bussiness.setBalance(new BigDecimal(0));
        bussiness.setBussCreousel("");
        bussiness.setBussInfo("");
        bussiness.setSex(" ");
        bussiness.setBussLogo("");
        bussiness.setFreezeMoney(BigDecimal.valueOf(0));

        bussiness.setCreated(new Date());
        bussiness.setDispatching(new BigDecimal(0));
        bussiness.setHeadPic("");
        bussiness.setRegisterNumber(registerNumber);
        bussiness.setIdCard("");
        //昵称
        String str = "****";
        StringBuilder sb = new StringBuilder(account);
        sb.replace(3, 7, str);
        bussiness.setBussName("商家" + sb.toString());
        bussiness.setIsInvoice(0);
        bussiness.setIsRecommend(0);
        bussiness.setPwd(MD5Util.md5(pwd));
        bussiness.setReason("");
        bussiness.setStartTime("00:00");
        bussiness.setEndTime("23:00");
        bussiness.setState(1);
        bussiness.setIsPosition(0);
        bussiness.setIsOpen(2);
        bussiness.setCashPwd("");
        Long bussId = bussinessDao.save(bussiness);
        Map<String, Object> map = new HashMap<String, Object>();
        trendService.saveUser(account, pwd, bussId.intValue(), "", account, "", 2);
        map.put("id", bussId);
        String header = trendService.getToken(bussId.intValue(), 2).get("accessToken").toString();
        String trendsUserId = "";
        trendsUserId = trendService.getToken(bussId.intValue(), 2).get("uniqueId").toString();
        map.put("trendsUserId", trendsUserId);
        String ryToken = RongYunUtils.getRYToken("company" + bussId, "", "");
        System.out.println(ryToken);
        bussinessDao.updateRYToken(bussId, ryToken, trendsUserId);
        String token = TokenUtils.putValue(map, 30);
        //修改最后登录时间
        bussinessDao.updateLastLoginTime(account);
        //添加互动用户表中
        trendsUserService.addTrendsUser(0, bussId.intValue());
        map.put("token", token);
        map.put("header", header);
//        map.put("id", bussiness.getId());
        map.put("cityId", bussiness.getCityId());
        map.put("isOpen", bussiness.getIsOpen());
        map.put("startTime", bussiness.getStartTime());
        map.put("endTime", bussiness.getEndTime());
        map.put("registerNumber", registerNumber);
        return map;
    }


    /**
     * 忘记密码修改密码
     *
     * @param account 账号
     * @param newPwd  新密码
     * @return
     */
    @Override
    public boolean updateForgetPwd(String account, String newPwd) throws ServiceException {
        Bussiness bussiness = bussinessDao.getBussnessByPhone(account);
        trendService.updateInfo(bussiness.getId(), account, bussiness.getPwd(), account, 2, bussiness.getBussName(), bussiness.getHeadPic(), bussiness.getSex());
        return bussinessDao.updateForgetPwd(account, MD5Util.md5(newPwd)) > 0;
    }

    /**
     * 根据编号获取商家信息
     *
     * @param id 商家编号
     * @return
     */
    @Override
    public Bussiness getBusinessById(Integer id) throws ServiceException {
        Bussiness bussiness = bussinessDao.getEntityById(id);
        if (bussiness == null) {
            throw new ServiceException("商家不存在");
        }
        return bussiness;
    }

    /**
     * 获取商家个人信息
     *
     * @param bussId 商家编号
     * @return
     */
    @Override
    public Map<String, Object> getBussinessInfo(Integer bussId) throws ServiceException {
        Bussiness bussiness = getBusinessById(bussId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("headPic", bussiness.getHeadPic());
        map.put("busName", bussiness.getBussName());
        map.put("account", bussiness.getAccount());
        map.put("shopPic", bussiness.getShopPic());
        map.put("address", bussiness.getAdress());
        map.put("phone", bussiness.getBussPhone());
        map.put("servicePhone", bussiness.getBussTel());
        map.put("lat", bussiness.getLat());
        map.put("lng", bussiness.getLng());
        map.put("isOpen", bussiness.getIsOpen());
        map.put("backgroundImg", bussiness.getBackgroundImg());
        map.put("startTime", bussiness.getStartTime());
        map.put("endTime", bussiness.getEndTime());
        map.put("cityId", bussiness.getCityId());
        map.put("area", bussiness.getArea());
        map.put("sex", bussiness.getSex());
//        String provinceName = cityService.getCityNameById(bussiness.getProvincesId());
        String cityName = cityService.getCityNameById(bussiness.getCityId());
//        String areaName = cityService.getCityNameById(bussiness.getAreaId());
//        map.put("provinceName", provinceName);
        map.put("cityName", cityName);
//        map.put("areaName", areaName);
        //今日收入
        Double todayMoney = orderService.getBussinessTodayMoney(bussId, DateUtil.getCurrentDateFormat());
        map.put("todayMoney", todayMoney);
        //今日订单
        Integer todayOrderNumber = orderService.getBussinessTodayOrder(bussId, DateUtil.getCurrentDateFormat());
        map.put("todayOrderNumber", todayOrderNumber);
        //全部订单
        Integer allOrderNumber = orderService.getAllOrderNumber(bussId);
        map.put("allOrderNumber", allOrderNumber);
        int isRecord = companyPanymentHistoryDao.getCountRecord(bussiness.getId());
        map.put("isRecord", isRecord);
        //返回提现到账时间
        map.put("cashTime", paramsService.getParamsValue(29, 27).get("value"));
        return map;
    }

    /**
     * 修改商家个人信息
     *
     * @param bussId  商家编号
     * @param headPic 头像
     * @param name    名称
     * @param sex
     * @return
     */
    @Override
    public boolean updateBusinessInfo(Integer bussId, String headPic, String name, String hxKid, String sex) throws ServiceException {
        Bussiness bussiness = bussinessDao.getEntityById(bussId);
        if (bussiness == null) {
            throw new ServiceException("商家不存在");
        }
        trendService.updateInfo(bussiness.getId(), bussiness.getAccount(), bussiness.getPwd(), bussiness.getAccount(), 2, name, headPic, sex);
        String userId = JSONObject.fromObject(bussiness.getRyToken()).get("userId").toString();
        RongYunUtils.refreshInfo(userId, name, headPic);
        int trendsUserId = trendsUserService.getTrendsUserIdByBussId(bussiness.getId());
//        trendsUserService.updateUserInfo(trendsUserId, name, headPic);
        ryFriendService.updateHeadPic(userId, "http://www.taoshunda.com/images/" + headPic, sex, name);
        return bussinessDao.updateBusinessInfo(bussId, headPic, name, sex) > 0;
    }

    /**
     * 获取更换账号时老手机号的验证码
     *
     * @param bussId 商家编号
     * @return
     */
    @Override
    public boolean getChangeAccountOldMobileMsg(Integer bussId) throws ServiceException {
        Bussiness bussiness = getBusinessById(bussId);
        if (bussiness == null) {
            throw new ServiceException("商家不存在");
        }
        //1.获取验证码
        return MsgUtils.sendMsg(bussiness.getAccount(), SMSConstants.msgCodeTemplate);
    }

    /**
     * 获取更换账号时新手机号的验证码
     *
     * @param mobile 手机号
     * @return
     */
    @Override
    public boolean getChangeAccountNewMobileMsg(String mobile) throws ServiceException {
        //1.判断账号是否存在
        Bussiness bussiness = bussinessDao.getBussnessByPhone(mobile);
        if (bussiness != null) {
            throw new ServiceException("该账号已注册");
        }
        return MsgUtils.sendMsg(mobile, SMSConstants.msgCodeTemplate);
    }

    /**
     * 修改账号
     *
     * @param bussId     商家编号
     * @param newAccount 账号
     * @return
     */
    @Override
    public boolean changeAccount(Integer bussId, String newAccount) throws ServiceException {
        Bussiness bussiness = bussinessDao.getCompanyById(bussId);
        trendService.updateInfo(bussiness.getId(), newAccount, bussiness.getPwd(), newAccount, 2, bussiness.getBussName(), bussiness.getHeadPic(), bussiness.getSex());
        return bussinessDao.updateBussinessAccount(bussId, newAccount) > 0;
    }

    /**
     * 验证密码
     *
     * @param bussId 商家编号
     * @param pwd    密码
     * @return
     */
    @Override
    public boolean checkPwd(Integer bussId, String pwd) throws ServiceException {
        Bussiness bussiness = getBusinessById(bussId);
        if (!bussiness.getPwd().equals(MD5Util.md5(pwd))) {
            throw new ServiceException("密码不正确");
        }
        return true;
    }

    /**
     * 修改密码
     *
     * @param bussId  商家编号
     * @param pwd     密码
     * @param surePwd 确认密码
     * @return
     */
    @Override
    public boolean updatePwd(Integer bussId, String pwd, String surePwd) throws ServiceException {
        Bussiness bussiness = getBusinessById(bussId);
//        if (!pwd.equals(surePwd)) {
//            throw new ServiceException("两次密码不一致");
//        }
        return bussinessDao.updatePwd(bussId, MD5Util.md5(pwd)) > 0;
    }

    /**
     * 推荐商家广告位
     *
     * @param id
     * @param cityId
     * @param isPosition
     * @param storePic
     * @param carouselId
     * @return
     */
    @Override
    public int updateIsPosition(Integer id, Integer cityId, Integer isPosition, Integer state, String storePic, Integer carouselId) throws ServiceException {
        if (isPosition == 1) {
            if (state == 2) {
                throw new ServiceException("该商家已被禁用");
            }
            Carousel carousel = new Carousel();
            carousel.setCityId(cityId);
            carousel.setLink(String.valueOf(id));
            carousel.setPicPath(storePic);
            carousel.setStatus(1);
            carousel.setCreated(new Date());
            carouselDao.save(carousel);
            return bussinessDao.updateIsPosition(id, isPosition);
        } else {
            carouselDao.updateStatus(carouselId);
            return bussinessDao.updateIsPosition(id, isPosition);
        }
    }

    /**
     * 查询推荐商家
     *
     * @param name
     * @param cityName
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page queryRecommendBusiness(String name, String cityName, int nowPage, int pageSize) {
        return bussinessDao.queryRecommendBusiness(name, cityName, nowPage, pageSize);
    }

    /**
     * 删除推荐商家
     *
     * @param id
     * @param isRecommend
     * @return
     */
    @Override
    public int updateIsRecommend(Integer id, Integer isRecommend) {
        return bussinessDao.updateRecommend(id, isRecommend);
    }

    /**
     * 查询推荐广告位
     *
     * @param name
     * @param cityId
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page queryRecommendAdv(String name, Integer cityId, int nowPage, int pageSize) {
        return bussinessDao.queryRecommendAdv(name, cityId, nowPage, pageSize);
    }

    /**
     * 查看优惠券
     *
     * @param id
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page<Map<String, Object>> examineCoupon(Integer id, int nowPage, int pageSize) {
        return couponDao.examineCoupon(id, nowPage, pageSize);
    }

    /**
     * 查看优惠活动
     *
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> examineActivity(Integer id) {
        return promotionDao.examineActivity(id);
    }

    /**
     * 修改是否营业
     *
     * @param bussId 商家编号
     * @param isOpen 是否营业
     * @return
     */
    @Override
    public boolean updateShopIsOpen(Integer bussId, int isOpen) {
        return bussinessDao.updateShopIsOpen(bussId, isOpen) > 0;
    }

    @Override
    public List<Map<String, Object>> getBusinessByKey(int cityId, String key, double ulat, double ulng, int bussTypeId, int nowPage, int pageSize) throws ServiceException {

        try {
            List<Map<String, Object>> mapList = bussinessDao.getBusinessByKey(cityId, key, bussTypeId, nowPage, pageSize, "");
            for (int i = 0; i < mapList.size(); i++) {
                //获取商家编号
                int busId = Integer.parseInt(mapList.get(i).get("id").toString());
                //遍历获取商家的优惠劵
                List<Map<String, Object>> couponList = couponDao.getCouponByBussId(busId);
                if (couponList.size() > 0) {
                    mapList.get(i).put("couponList", couponList);
                }
                //遍历获取商家的优惠活动
                List<Map<String, Object>> promotionList = promotionDao.getPromotionByBussId(busId);
                if (promotionList.size() > 0) {
                    mapList.get(i).put("promotionList", promotionList.get(0).get("name"));
                } else {
                    mapList.get(i).put("promotionList", "");
                }

            }
            mapList = Spatial4jUtil.getComparedList(ulng, ulat, mapList);
            for (int i = 0; i < mapList.size(); i++) {
                Map item = mapList.get(i);
                int busId = Integer.parseInt(item.get("id").toString());
                BigDecimal bigDecimal = new BigDecimal(item.get("distance").toString());
                double dispatching = getDispatching(busId, bigDecimal.setScale(2, RoundingMode.HALF_EVEN), 0);
                item.put("dispatching", dispatching);
            }
            return mapList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("当前GPS信号弱");
        }

    }

    @Override
    public Map<String, Object> getBusinessByKeyPc(int cityId, String key, double ulat, double ulng, int bussTypeId, int nowPage, int pageSize, String address) throws ServiceException {

        try {
            List<Map<String, Object>> mapList = bussinessDao.getBusinessByKey(cityId, key, bussTypeId, nowPage, pageSize, address);
            int total = bussinessDao.getTotalByKey(cityId, key, bussTypeId);
            for (int i = 0; i < mapList.size(); i++) {
                //获取商家编号
                int busId = Integer.parseInt(mapList.get(i).get("id").toString());
                //遍历获取商家的优惠劵
                List<Map<String, Object>> couponList = couponDao.getCouponByBussId(busId);
                if (couponList.size() > 0) {
                    mapList.get(i).put("couponList", couponList);
                }
                //遍历获取商家的优惠活动
                List<Map<String, Object>> promotionList = promotionDao.getPromotionByBussId(busId);
                if (promotionList.size() > 0) {
                    mapList.get(i).put("promotionList", promotionList.get(0).get("name"));
                } else {
                    mapList.get(i).put("promotionList", "");
                }

            }
            mapList = Spatial4jUtil.getComparedList(ulng, ulat, mapList);
            for (int i = 0; i < mapList.size(); i++) {
                Map item = mapList.get(i);
                int busId = Integer.parseInt(item.get("id").toString());
                BigDecimal bigDecimal = new BigDecimal(item.get("distance").toString());
                double dispatching = getDispatching(busId, bigDecimal.setScale(2, RoundingMode.HALF_EVEN), 0);
                item.put("dispatching", dispatching);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("list", mapList);
            map.put("total", total);
            return map;
        } catch (Exception e) {
            throw new ServiceException("当前GPS信号弱");
        }

    }

    @Override
    public Map<String, Object> getBussinessListPc(int cityId, double ulat, double ulng, int typeId, int nowPage, int pageSize, int bussTypeId, int userId) throws ServiceException {
        //接收所有商家
        List<Map<String, Object>> mapList = bussinessDao.getBussinessList(typeId, cityId, nowPage, pageSize, bussTypeId, userId, ulat, ulng);
        int total = bussinessDao.getTotal(typeId, cityId, bussTypeId, userId);
        for (int i = 0; i < mapList.size(); i++) {
            //获取商家编号
            int busId = Integer.parseInt(mapList.get(i).get("id").toString());
            //遍历获取商家的优惠劵
            List<Map<String, Object>> couponList = couponDao.getCouponByBussId(busId);
            if (couponList.size() > 0) {
                mapList.get(i).put("couponList", couponList);
            }
            //遍历获取商家的优惠活动
            List<Map<String, Object>> promotionList = promotionDao.getPromotionByBussId(busId);
            if (promotionList.size() > 0) {
                mapList.get(i).put("promotionList", promotionList.get(0).get("name"));
            } else {
                mapList.get(i).put("promotionList", "");
            }

        }
        //判断是否是按照距离排序
        if (typeId != 3) {
            int len = mapList.size();
            for (int i = 0; i < len; ++i) {
                Map item = mapList.get(i);
                int busId = Integer.parseInt(item.get("id").toString());
                if (null == item.get("lng") || null == item.get("lat")) {
                    throw new ServiceException("请在参数集合中设置经度(lng)和纬度(lat)");
                }
                double distance = Spatial4jUtil.getDistance(ulng, ulat, Double.valueOf(item.get("lng").toString()).doubleValue(), Double.valueOf(item.get("lat").toString()).doubleValue());
                BigDecimal bigDecimal = new BigDecimal(distance);
                item.put("distance", bigDecimal.setScale(2, RoundingMode.HALF_EVEN));
                double dispatching = getDispatching(busId, bigDecimal.setScale(2, RoundingMode.HALF_EVEN), 0);
                item.put("dispatching", dispatching);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("list", mapList);
            map.put("total", total);
            return map;
        } else {
            try {
                mapList = Spatial4jUtil.getComparedList(ulng, ulat, mapList);
                for (int i = 0; i < mapList.size(); i++) {
                    Map item = mapList.get(i);
                    int busId = Integer.parseInt(item.get("id").toString());
                    BigDecimal bigDecimal = new BigDecimal(item.get("distance").toString());
                    double dispatching = getDispatching(busId, bigDecimal.setScale(2, RoundingMode.HALF_EVEN), 0);
                    item.put("dispatching", dispatching);
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("list", mapList);
                map.put("total", total);
                return map;
            } catch (Exception e) {
                e.printStackTrace();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("list", mapList);
                map.put("total", total);
                return map;
            }
        }
    }


    @Override
    public Map<String, Object> getDispatching(double ulat, double ulng, int bussId, int isFree) throws ServiceException {
        Bussiness bussiness = bussinessDao.getEntityById(bussId);
        if (bussiness == null) {
            throw new ServiceException("该商家信息不存在");
        }
        //获取商家的经纬度
        double buslng = Double.parseDouble(bussiness.getLng());
        double buslat = Double.parseDouble(bussiness.getLat());
        //计算距离
        double distace = Spatial4jUtil.getDistance(ulng, ulat, buslng, buslat);
//        getDispatching(bussId, BigDecimal.valueOf(distace));
        Map<String, Object> map = new HashedMap();
        map.put("money", getDispatching(bussId, BigDecimal.valueOf(distace), isFree));
        return map;
    }

    /**
     * 查询未通过的商家
     *
     * @param businessName
     * @param account
     * @param telephone
     * @param cityName
     * @param address
     * @param nowPage
     * @param pageSize
     * @return
     */
    @Override
    public Page queryNotBusiness(String businessName, String account, String telephone, String cityName, String address, int nowPage, int pageSize) {
        return bussinessDao.queryNotBusiness(businessName, account, telephone, cityName, address, nowPage, pageSize);
    }

    /**
     * 修改商家的背景图片
     *
     * @param bussId        商家编号
     * @param backgroundPic 背景图片
     * @return
     */
    @Override
    public boolean updateBussinessBackgroundPic(Integer bussId, String backgroundPic) {
        return bussinessDao.updateBussinessBackgroundPic(bussId, backgroundPic) > 0;
    }

    /**
     * 修改商家余额并添加账单
     *
     * @param bussId  商家编号
     * @param money   余额
     * @param refunds
     * @return
     */
    @Override
    public boolean updateBussinessBalance(Integer bussId, Double money, Integer sourceType, String orderNumber, int refunds) throws ServiceException {
        Bussiness bussiness = getBusinessById(bussId);
        Double afterMoney;
        if (sourceType == 1) {
            afterMoney = MathUtils.add(bussiness.getBalance().doubleValue(), money);
        } else {
            afterMoney = MathUtils.sub(bussiness.getBalance().doubleValue(), money);
        }

        if (afterMoney < 0) {
            throw new ServiceException("商家余额不足");
        }
        bussinessDao.updateBussinessBalance(bussId, afterMoney);
        String balanceState = "+";
        if (sourceType != 1) {
            balanceState = "-";
        }
        //添加账单
        CompanyBalance companyBalance = new CompanyBalance();
        companyBalance.setBalance(BigDecimal.valueOf(money));
        companyBalance.setBalanceState(balanceState);
        companyBalance.setBussId(bussId);
        companyBalance.setCreated(new Date());
        companyBalance.setCurrentAmount(BigDecimal.valueOf(afterMoney));
        companyBalance.setOrderNumber(orderNumber);
        companyBalance.setSourceType(sourceType);
        return companyBalanceDao.save(companyBalance) > 0;
    }


    @Override
    public Map<String, Object> getBusinessByAddress(int cityId, String address, int bussTypeId, int nowPage, int pageSize, double ulng, double ulat) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<Map<String, Object>> mapList = bussinessDao.getBusinessByAddress(cityId, address, bussTypeId, nowPage, pageSize);
            int total = bussinessDao.getTotal(cityId, address, bussTypeId);
            for (int i = 0; i < mapList.size(); i++) {
                //获取商家编号
                int busId = Integer.parseInt(mapList.get(i).get("id").toString());
                //遍历获取商家的优惠劵
                List<Map<String, Object>> couponList = couponDao.getCouponByBussId(busId);
                if (couponList.size() > 0) {
                    mapList.get(i).put("couponList", couponList);
                }
                //遍历获取商家的优惠活动
                List<Map<String, Object>> promotionList = promotionDao.getPromotionByBussId(busId);
                if (promotionList.size() > 0) {
                    mapList.get(i).put("promotionList", promotionList.get(0).get("name"));
                } else {
                    mapList.get(i).put("promotionList", "");
                }

            }
            mapList = Spatial4jUtil.getComparedList(ulng, ulat, mapList);
            for (int i = 0; i < mapList.size(); i++) {
                Map item = mapList.get(i);
                int busId = Integer.parseInt(item.get("id").toString());
                BigDecimal bigDecimal = new BigDecimal(item.get("distance").toString());
                double dispatching = getDispatching(busId, bigDecimal.setScale(2, RoundingMode.HALF_EVEN), 0);
                item.put("dispatching", dispatching);
            }
            map.put("list", mapList);
            map.put("total", total);

        } catch (Exception e) {
            throw new ServiceException("");
        }
        return map;

    }


    /**
     * 查询商家优惠活动
     *
     * @param businessName
     * @param nowPage
     * @param pageSize
     * @return
     */
    @Override
    public Page queryBusinessActivity(String businessName, int nowPage, int pageSize) {
        return bussinessDao.queryBusinessActivity(businessName, nowPage, pageSize);
    }

    /**
     * 根据城市查询商家
     *
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> queryBusinessCity(Integer id) {
        return bussinessDao.queryBusinessCity(id);
    }


    /**
     * 查看商家详情
     *
     * @param id 商家编号
     * @return
     */
    @Override
    public Map<String, Object> getBussDetails(Integer id) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        Bussiness bussiness = getBusinessById(id);
        map.put("startTime", bussiness.getStartTime());
        map.put("endTime", bussiness.getEndTime());
        map.put("headPic", bussiness.getHeadPic());
        map.put("phone", bussiness.getBussTel());
        map.put("provinceId", bussiness.getProvincesId());
        map.put("cityId", bussiness.getCityId());
        map.put("areaId", bussiness.getAreaId());
//        String provinceName = cityService.getCityNameById(bussiness.getProvincesId());
        String cityName = cityService.getCityNameById(bussiness.getCityId());
//        String areaName = cityService.getCityNameById(bussiness.getAreaId());
//        map.put("provinceName", provinceName);
        map.put("cityName", cityName);
        map.put("cityId", bussiness.getCityId());
        map.put("area", bussiness.getArea());
//        map.put("areaName", areaName);
        map.put("address", bussiness.getAdress());
        map.put("bussLicnese", bussiness.getBussLicnese());
        map.put("serviceLince", bussiness.getServiceLince());
        map.put("otherLicenses", bussiness.getOtherLicenses());
        map.put("otherLicensesTwo", bussiness.getOtherLicensesTwo());
        map.put("lat", bussiness.getLat());
        map.put("lng", bussiness.getLng());
        map.put("isDispatching", bussiness.getIsDispatching());
        map.put("isInvoice", bussiness.getIsInvoice());
        map.put("storePic", bussiness.getStorePic());
        map.put("shopPic", bussiness.getShopPic());
        return map;
    }

    /**
     * 修改商家详情信息
     *
     * @param id               商家编号
     * @param startTime        开始时间
     * @param endTime          结束时间
     * @param phone            电话
     * @param area             地区
     * @param cityId           城市编号
     * @param address          地址
     * @param lat              纬度
     * @param lng              经度
     * @param isDispatching    是否有配送费
     * @param isInvoice
     * @param storePic
     * @param shopPic          @return
     * @param provinceId
     * @param areaId
     * @param otherLicenses
     * @param otherLicensesTwo
     * @param bussLicnese
     * @param serviceLince
     */
    @Override
    public boolean updateBussDetails(Integer id, String startTime, String endTime, String phone, String area, Integer cityId, String address, String lat, String lng, Integer isDispatching, String isInvoice, String storePic, String shopPic, Integer provinceId, Integer areaId, String otherLicenses, String otherLicensesTwo, String bussLicnese, String serviceLince) {
        //修改商家轮播图的经纬度
        int minCityId;
        if (areaId == 0) {
            minCityId = cityId;
        } else {
            minCityId = areaId;
        }
        carouselDao.updateCarouselInfo(id, lat, lng, cityId);
        goodsDao.updateGoodsCity(minCityId, id);
        return bussinessDao.updateBussDetails(id, startTime, endTime, phone, area, cityId, address, lat, lng, isDispatching, isInvoice, shopPic, storePic, provinceId, areaId, minCityId, otherLicenses, otherLicensesTwo, bussLicnese, serviceLince) > 0;
    }

    /**
     * 推荐商家审核
     *
     * @param nowPage
     * @param pageSize
     * @param businessName
     * @return
     */
    @Override
    public Page queryAuditingBusiness(int nowPage, int pageSize, String businessName) {
        return recommendCompanyDao.queryAuditingBusiness(nowPage, pageSize, businessName);
    }

    /**
     * 同意推荐商家审核
     *
     * @param id
     * @param picture
     * @return
     */
    @Override
    public int replaceBusinessPicture(Integer id, String picture) {
        //查询推荐商家的缴费信息
        Map<String, Object> map = companyPanymentHistoryDao.getRecommend(id);
        String num = map.get("paymentTime").toString();
        int month = Integer.parseInt(num);
        //系统时间
        Date time = new Date();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, month);
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = dft.format(time.getTime());//系统时间  ---开始时间
        String endTime = dft.format(cal.getTime());//系统时间+月份 ---结束时间
        return recommendCompanyDao.replaceBusinessPicture(id, picture, currencyCode.同意申请.getCode(), startTime, endTime);
    }

    /**
     * @param id
     * @param picture
     * @return
     */
    @Override
    public int updatePic(Integer id, String picture) {
        return recommendCompanyDao.updatePic(id, picture);
    }

    /**
     * 添加设置提现密码
     *
     * @param bussId
     * @param cashPwd
     * @return
     */
    @Override
    public boolean addCashPwd(Integer bussId, String cashPwd) {
        return bussinessDao.addCashPwd(bussId, cashPwd);
    }

    @Override
    public Map<String, Object> getCashPwd(Integer bussId) {
        Bussiness bussiness = bussinessDao.getEntityById(bussId);
        Map map = new HashedMap();
        map.put("cashPwd", bussiness.getCashPwd());
        return map;
    }

    /**
     * @param orderNumber
     * @param nowPage
     * @param pageSize    @return
     */
    @Override
    public Page businessOrderDetail(String orderNumber, int nowPage, int pageSize) {
        return orderDetailsDao.businessOrderDetail(orderNumber, nowPage, pageSize);
    }

    /**
     * 添加商家冻结金额
     *
     * @param sellerId
     * @param money
     */
    @Override
    public void updateFreezeMoney(Integer sellerId, double money) {
        bussinessDao.updateFreezeMoney(sellerId, money);
    }

    @Override
    public int getCompanyCountByTypeId(Integer id) {

        return bussinessDao.getCompanyCountByTypeId(id);
    }

    @Override
    public Integer getRebateCount(Integer userId) {
        return bussinessDao.getRebateCount(userId);
    }

    @Override
    public boolean saveCompanyBalance(Integer sellerId, double companyGetMoney, Integer sourceType, String orderNumber, int refunds) throws ServiceException {
        Bussiness bussiness = getBusinessById(sellerId);
        Double afterMoney;
        if (sourceType == 1) {
            afterMoney = MathUtils.add(bussiness.getBalance().doubleValue(), bussiness.getFreezeMoney().doubleValue(), companyGetMoney);
        } else {
            afterMoney = MathUtils.sub(bussiness.getBalance().add(bussiness.getFreezeMoney()).doubleValue(), companyGetMoney);
        }
        String balanceState = "+";
        if (sourceType != 1) {
            balanceState = "-";
        }
        //添加账单
        CompanyBalance companyBalance = new CompanyBalance();
        companyBalance.setBalance(BigDecimal.valueOf(companyGetMoney));
        companyBalance.setBalanceState(balanceState);
        companyBalance.setBussId(sellerId);
        companyBalance.setCreated(new Date());
        companyBalance.setCurrentAmount(BigDecimal.valueOf(afterMoney));
        companyBalance.setOrderNumber(orderNumber);
        companyBalance.setSourceType(sourceType);
        return companyBalanceDao.save(companyBalance) > 0;
    }

    /**
     * 功能描述:
     *
     * @param companyId           商家编号
     * @param area                地区
     * @param provinceId          省份编号
     * @param registerNumber      注册步数
     * @param servicePhone        服务电话
     * @param name                商家名称
     * @param address             商家地址
     * @param cityId              市级编号
     * @param areaId              区级编号
     * @param typeId              商家类型编号
     * @param lat                 商家纬度
     * @param lng                 商家经度
     * @param legalPeople         法人
     * @param emergencyContact    紧急联系人
     * @param emergencyContactTel 紧急联系人电话
     * @return:
     * @auther: wsl
     * @date: 2019/2/26 9:24
     */
    @Override
    public Map registerSecondStep(Integer companyId, String area, Integer provinceId, Integer registerNumber, String servicePhone, String name, String address, Integer cityId, Integer areaId, Integer typeId, String lat, String lng, String legalPeople, String emergencyContact, String emergencyContactTel) {
        //修改商家轮播图的经纬度
        int minCityId;
        if (areaId == 0) {
            minCityId = cityId;
        } else {
            minCityId = areaId;
        }
        boolean flag = bussinessDao.registerSecondStep(companyId, area, provinceId, registerNumber, servicePhone, name, address, cityId, areaId, typeId, lat, lng
                , legalPeople, emergencyContact, emergencyContactTel, minCityId);
        Bussiness bussiness = bussinessDao.getEntityById(companyId);
        Map map = new HashMap();
        map.put("id", bussiness.getId());
        if (bussiness.getBussTypeId() != null) {
            map.put("id", bussiness.getId());
            //isAuthentication   0   未认证  1已认证
            map.put("isAuthentication", 1);
            String token = TokenUtils.putValue(bussiness.toMap(), 30);
            String hander = trendService.getToken(bussiness.getId(), 2).get("accessToken").toString();
            map.put("token", token);
            map.put("hander", hander);
            bussinessDao.updateLastLoginTime(bussiness.getAccount());
            map.put("cityId", bussiness.getCityId());
            map.put("areaId", bussiness.getAreaId());
            map.put("provincesId", bussiness.getProvincesId());
            map.put("minCityId", bussiness.getMinCityId());
            map.put("busName", bussiness.getBussName());
            map.put("typeId", bussiness.getBussTypeId());
            map.put("RyToken", JSONObject.fromObject(bussiness.getRyToken()).get("token"));
            map.put("RyId", JSONObject.fromObject(bussiness.getRyToken()).get("userId"));
            map.put("legalPeople", bussiness.getLegalPeople());
            int isRecord = companyPanymentHistoryDao.getCountRecord(bussiness.getId());
            int isRecordReturn = businessMoneyRecordDao.getCountAboutStates(bussiness.getId());
            map.put("isRecord", isRecord);
            map.put("audit", bussiness.getAudit());
            map.put("registerNumber", bussiness.getRegisterNumber());
            map.put("isRecordReturn", isRecordReturn);
        } else {
            map.put("registerNumber", bussiness.getRegisterNumber());
            map.put("isAuthentication", 0);
        }
        return map;
    }

    /**
     * 功能描述: 商家注册第三步
     *
     * @param companyId      商家编号
     * @param registerNumber 注册步数
     * @param storePic       商家编号
     * @param shopPic        商家编号
     * @param handheldPhotos 商家编号
     * @param fontCard       商家编号
     * @param reverseCard    商家编号
     * @param bussLicnese    商家编号
     * @param serviceLince   商家编号
     * @param legalCardPic   法人
     * @return:
     * @auther: wsl
     * @date: 2019/2/26 9:39
     */
    @Override
    public boolean registerThreeStep(Integer companyId, Integer registerNumber, String storePic, String shopPic, String legalCardPic, String handheldPhotos, String fontCard, String reverseCard, String bussLicnese, String serviceLince) {
        return bussinessDao.registerThreeStep(companyId, registerNumber, storePic, shopPic, legalCardPic, handheldPhotos, fontCard, reverseCard, bussLicnese, serviceLince);
    }


}
